const Base = require('./base.js');

module.exports = class extends Base {
  _isCheckLogin() {
    return false;
  }
  // 添加订单
  async addOrderAction() {
    const user = await this.ctx.session('login');

    if (!user || !user.id) {
      return this.fail('用户未登录，请先登录');
    }

    const { total_amount, remarks } = this.post();

    // eslint-disable-next-line no-console
    console.log(total_amount, remarks);

    // 将 total_amount 转换为数字
    const totalAmountNumber = parseFloat(total_amount); // 将字符串转换为浮动类型

    // eslint-disable-next-line no-console
    console.log(total_amount, remarks);

    if (isNaN(totalAmountNumber) || totalAmountNumber <= 0) {
      return this.fail('无效的订单金额');
    }

    // 初始化订单模型
    const orderModel = think.model('orders');

    const orderData = await orderModel.add({
      user_id: user.id,
      total_amount: totalAmountNumber, // 使用数字类型的 total_amount
      remarks
    });

    return this.success({data: orderData}, '订单添加成功');
  }

  // eslint-disable-next-line no-dupe-class-members
  async addOrderitemAction() {
    const user = await this.ctx.session('login');
    const { goods_id, num, order_id } = this.post();
    // eslint-disable-next-line no-console
    console.log(goods_id, num, order_id);

    if (!goods_id || num <= 0) {
      return this.fail('商品 ID 或数量无效');
    }

    // eslint-disable-next-line no-console
    console.log(goods_id, num, order_id);

    const orderItemModel = think.model('order_items');
    await orderItemModel.add({
      order_id,
      goods_id,
      quantity: num
    });

    return this.success({}, '订单添加成功');
  }

  async getOrdersAction() {
    const user = await this.ctx.session('login');
    if (!user || !user.id) {
      return this.fail('用户未登录，请先登录');
    }

    const ordersModel = think.model('orders');
    const orderItemsModel = think.model('order_items');
    const goodsModel = think.model('goods');

    // 获取用户的所有订单
    const orders = await ordersModel.where({ user_id: user.id }).select();
    if (!orders.length) {
      return this.success([], '没有找到相关订单数据');
    }

    // 获取所有订单项
    const orderIds = orders.map(order => order.id);
    const orderItems = await orderItemsModel.where({ order_id: ['IN', orderIds] }).select();

    // 获取商品信息
    const goodsIds = orderItems.map(item => item.goods_id);
    const goods = await goodsModel.where({ id: ['IN', goodsIds] }).select();

    // 将订单和订单项与商品信息关联
    const ordersWithItems = orders.map(order => {
      const items = orderItems.filter(item => item.order_id === order.id);

      // 将每个订单项与对应的商品数据关联
      const itemsWithGoods = items.map(item => {
        const good = goods.find(g => g.id === item.goods_id);
        return {
          ...item, // 保留原有的订单项信息
          goods: good ? {
            id: good.id,
            category_id: good.category_id,
            name: good.name,
            price: good.price,
            picture: good.picture,
            stock: good.stock,
            spec: good.spec,
            description: good.description
          } : null // 如果没有找到对应的商品，则设置为 null
        };
      });

      return {
        ...order,
        items: itemsWithGoods // 将商品数据嵌入到订单项中
      };
    });

    // 返回包含订单及其商品数据的结果
    return this.success(ordersWithItems, '订单数据获取成功');
  }

  // 修改订单状态
  async updateOrderAction() {
    const user = await this.ctx.session('login');

    if (!user || !user.id) {
      return this.fail('用户未登录，请先登录');
    }

    const { orderId, statu } = this.post();
    const orderModel = think.model('orders');

    const result = await orderModel.where({ id: orderId }).update({
      order_status: statu
    });

    if (result) {
      return this.success({}, '已收货');
    } else {
      return this.fail({}, '更新状态失败');
    }
  }

  // 评价订单
  async reviewOrderAction() {
    const user = await this.ctx.session('login');

    if (!user || !user.id) {
      return this.fail('用户未登录，请先登录');
    }

    const { review, reviewStar, orderId } = this.post();
    const orderModel = think.model('orders');
    const result = await orderModel.where({ id: orderId }).update({
      order_status: 2,
      review,
      review_star: reviewStar
    });

    if (result) {
      return this.success({}, '评价成功，即将返回待评价订单列表');
    } else {
      return this.fail({}, '评价失败，请稍后重试！');
    }
  }

  // 删除订单
  async deleteOrderAction() {
    const user = await this.ctx.session('login');

    if (!user || !user.id) {
      return this.fail('用户未登录，请先登录');
    }

    const { orderId } = this.post();
    const orderModel = think.model('orders');

    const result = await orderModel.where({ id: orderId }).delete();

    if (result) {
      return this.success({}, '删除订单成功');
    } else {
      return this.fail({}, '删除订单失败，请重试');
    }
  }
};
